package com.szhuang.mobilesafe.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.szhuang.mobilesafe.R;
import com.szhuang.mobilesafe.tools.AppConstant;
import com.szhuang.mobilesafe.tools.StreamTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by szhuang on 2015/3/14.
 */
public class SplashActivity extends Activity {

    private boolean interceptFlag;
    private int currentProgress;
    private String info_version;
    private String saveFileName;
    private String description;
    private String apkurl;

    private Thread downLoadThread;
    private ProgressBar mProgress;
    private TextView version;
    private Dialog pd = null;

    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        version = (TextView) findViewById(R.id.version);
        version.setText("版本号：" + getVersionName());

        AlphaAnimation aa = new AlphaAnimation(0.3f, 1.0f);
        aa.setDuration(1000);
        findViewById(R.id.splash).startAnimation(aa);

        sp=getSharedPreferences("config",MODE_PRIVATE);

        setUpdate();

    }

    private void checkUpdate() {

        new Thread() {
            @Override
            public void run() {
                super.run();
                Message msg = Message.obtain();
                try {
                    URL url = new URL(AppConstant.SERVERURL);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(5000);
                    int code = urlConnection.getResponseCode();
                    if (code == 200) {
                        InputStream in = urlConnection.getInputStream();
//                        String result= StreamTools.readFromStream(in);
//                        String result=StreamTools.convertStreamToString(in);
                        String result = StreamTools.inputStream2String(in);
                        Log.i(AppConstant.TAG, "联网成功了" + result);
                        JSONObject obj = new JSONObject(result);
                        info_version = (String) obj.get("version");
                        description = (String) obj.get("description");
                        apkurl = (String) obj.get("apkurl");

                        if (getVersionName().equals(info_version)) {
                            msg.what = AppConstant.ENTER_MAIN;
                        } else {
                            msg.what = AppConstant.SHOW_UPDATE_DIALOG;
                        }
                    }
                } catch (IOException e) {
                    msg.what = AppConstant.NETWORK_ERROR;
                } catch (JSONException e) {
                    msg.what = AppConstant.JSON_ERROR;
                } finally {
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }

    private void showUpdateDialog() {
        AlertDialog.Builder builder=new AlertDialog.Builder(SplashActivity.this);

        LayoutInflater inflaterDl = LayoutInflater.from(this);
        RelativeLayout layout = (RelativeLayout) inflaterDl.inflate(R.layout.activity_dialog, null);


        //其他方式的取消
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                quickIntoHome();
            }
        });

        //对话框
        final Dialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(layout);


        //取消按钮
        Button btnCancel = (Button) layout.findViewById(R.id.dialog_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                quickIntoHome();
            }
        });

        //确定按钮
        Button btnOK = (Button) layout.findViewById(R.id.dialog_ok);
        btnOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    dialog.dismiss();
                    showDownloadDialog();
                } else {
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(), "没有sdcard,请安装后再试！", Toast.LENGTH_LONG).show();
                    quickIntoHome();
                }

            }
        });

        //关闭按钮
        ImageButton btnClose = (ImageButton) layout.findViewById(R.id.dialog_close);
        btnClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                quickIntoHome();
            }
        });


    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
        builder.setTitle("软件版本更新");

        final LayoutInflater inflater = LayoutInflater.from(SplashActivity.this);
        View v = inflater.inflate(R.layout.activity_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);

        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        pd = builder.create();
        pd.show();
        downloadApk();
    }

    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();


    }

    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        startActivity(i);

    }

    private void enterHome() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                SplashActivity.this.finish();
            }
        }, 3000);
    }

    private void  quickIntoHome(){
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        SplashActivity.this.finish();
    }

    private void setUpdate(){
        if(sp.getBoolean("update",true)){
            checkUpdate();
        }else{
            enterHome();
        }
    }

    String getVersionName() {
        PackageManager pm = getPackageManager();

        try {
            // 得到知道APK的功能清单文件
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            //int versionCode = info.versionCode;
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AppConstant.ENTER_MAIN:
                    enterHome();
                    break;
                case AppConstant.SHOW_UPDATE_DIALOG:
                    showUpdateDialog();
                    Toast.makeText(getApplicationContext(), description, Toast.LENGTH_LONG).show();
                    break;
                case AppConstant.JSON_ERROR:
                    enterHome();
                    Toast.makeText(getApplicationContext(), "Json解析出错！", Toast.LENGTH_SHORT).show();
                    break;
                case AppConstant.NETWORK_ERROR:
                    enterHome();
                    Toast.makeText(getApplicationContext(), "网络错误！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }


    };

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AppConstant.DOWN_UPDATE:
                    mProgress.setProgress(currentProgress);
                    break;
                case AppConstant.DOWN_OVER:
                    installApk();
                    break;
                case AppConstant.DOWN_URL_ERROR:
                    pd.dismiss();
                    Toast.makeText(SplashActivity.this, "URL错误！", Toast.LENGTH_LONG).show();
                    quickIntoHome();
                    break;
                case AppConstant.DOWN_IO_ERROR:
                    pd.dismiss();
                    Toast.makeText(SplashActivity.this, "IO错误！", Toast.LENGTH_LONG).show();
                    quickIntoHome();
                    break;
                default:
                    break;
            }
        }
    };

    private Runnable mdownApkRunnable = new Runnable() {

        @Override
        public void run() {
            try {
                URL url = new URL(apkurl);

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(AppConstant.SAVEPATH);
                if(!file.exists()){
                    file.mkdir();
                }
                saveFileName = AppConstant.SAVEPATH + "mobilesafe" + info_version + ".apk";
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do{
                    int numread = is.read(buf);
                    count += numread;
                    currentProgress =(int)(((float)count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(AppConstant.DOWN_UPDATE);
                    if(numread <= 0){
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(AppConstant.DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                mHandler.sendEmptyMessage(AppConstant.DOWN_URL_ERROR);
                e.printStackTrace();
            } catch(IOException e){
                Log.i(AppConstant.TAG,e.toString());
                mHandler.sendEmptyMessage(AppConstant.DOWN_IO_ERROR);
                e.printStackTrace();
            }

        }
    };
}
